/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managedbean;

import entity.Employee;
import entity.Message;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import org.primefaces.event.SelectEvent;
import session.stateless.MessageSessionBeanLocal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import session.stateless.ContactSessionBeanLocal;
import session.stateless.EmployeeSessionBeanLocal;

/**
 *
 * @author Wx
 */
@ManagedBean(name = "messageManagerBean")
@RequestScoped
public class MessageManagerBean implements Serializable {

    @ManagedProperty(value = "#{loginManagerBean}")
    private LoginManagerBean loginManagerBean;
    @ManagedProperty(value = "#{userSessionManagerBean}")
    private UserSessionManagerBean userSessionManagerBean;
    @EJB
    MessageSessionBeanLocal messageSessionBeanLocal;
    @EJB
    ContactSessionBeanLocal contactSessionBeanLocal;
    @EJB
    EmployeeSessionBeanLocal employeeSessionBeanLocal;
    //Message
    private Long messageId;
    private String senderId;
    private String receiverId;
    private String subject;
    private String content;
    private boolean messageStatus; //read keyword is a reserved SQL word
    private Timestamp messageDate;
    private String userId;
    private List<Message> messages;
    private Message message;
    private String type = "Inbox";
    private int count;
    private String loadMessagesPage;
    private String loadMessagePage;
    String serverName = FacesContext.getCurrentInstance().getExternalContext().getRequestServerName();
    String serverPort = "8080";
    private List<Employee> receivers;
    private String previousMessage;
    private Message selectedMessage;
    private Map<Long, Boolean> selectedIds = new HashMap<Long, Boolean>();
    private List<Message> selectedMessages;
    private Boolean isInbox;
    private Boolean deleteButtonStatus;

    /** Creates a new instance of MessageManagerBean */
    public MessageManagerBean() {
    }

    /**
     * @return the messageId
     */
    public Long getMessageId() {
        return messageId;
    }

    /**
     * @param messageId the messageId to set
     */
    public void setMessageId(Long messageId) {
        this.messageId = messageId;
    }

    /**
     * @return the senderId
     */
    public String getSenderId() {
        return senderId;
    }

    /**
     * @param senderId the senderId to set
     */
    public void setSenderId(String senderId) {
        this.senderId = senderId;
    }

    /**
     * @return the receiverId
     */
    public String getReceiverId() {
        return receiverId;
    }

    /**
     * @param receiverId the receiverId to set
     */
    public void setReceiverId(String receiverId) {
        this.receiverId = receiverId;
    }

    /**
     * @return the content
     */
    public String getContent() {
        return content;
    }

    /**
     * @param content the content to set
     */
    public void setContent(String content) {
        this.content = content;
    }

    /**
     * @return the messageStatus
     */
    public boolean isMessageStatus() {
        return messageStatus;
    }

    /**
     * @param messageStatus the messageStatus to set
     */
    public void setMessageStatus(boolean messageStatus) {
        this.messageStatus = messageStatus;
    }

    /**
     * @return the messageDate
     */
    public Timestamp getMessageDate() {
        return messageDate;
    }

    /**
     * @param messageDate the messageDate to set
     */
    public void setMessageDate(Timestamp messageDate) {
        this.messageDate = messageDate;
    }

    /**
     * @return the type
     */
    public String getType() {
        return type;
    }

    /**
     * @return the messages
     */
    public List<Message> getMessages() {
        return messages;
    }

    /**
     * @return the subject
     */
    public String getSubject() {
        return subject;
    }

    /**
     * @param subject the subject to set
     */
    public void setSubject(String subject) {
        this.subject = subject;
    }

    /**
     * @param type the type to set
     */
    public void setType(String type) {
        this.type = type;
    }

    /**
     * @param messages the messages to set
     */
    public void setMessages(List<Message> messages) {
        this.messages = messages;
    }

    /**
     * @return the count
     */
    public int getCount() {
        return count;
    }

    /**
     * @param count the count to set
     */
    public void setCount(int count) {
        this.count = count;
    }

    /**
     * @return the loadMessagesPage
     */
    public String getLoadMessagesPage() { //run onload of messages.xhtml
        this.setUserId(userSessionManagerBean.getUserId());
        this.setType(userSessionManagerBean.getMessageType());

        loadMessages();

        return null;
    }

    /**
     * @param loadMessagePage the loadMessagePage to set
     */
    public void setLoadMessagesPage(String loadMessagePage) {
        this.loadMessagesPage = loadMessagePage;
    }

    /**
     * @return the message
     */
    public Message getMessage() {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(Message message) {
        this.message = message;
    }

    /**
     * @return the loadMessagePage
     */
    public String getLoadMessagePage() {
        try {
            message = userSessionManagerBean.getSelectedMessage();

            setMessageId(message.getMessageId());
            setSenderId(message.getSenderId());
            setReceiverId(message.getReceiverId());
            setSubject(message.getSubject());
            setMessageDate(message.getMessageDate());
            
            SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm a");
            
            StringBuilder sb = new StringBuilder(sdf.format(getMessageDate()));
            
            setContent("<br><br><br><hr>Message sent on "
                    + sb
                    + "<br><hr>"
                    + message.getContent());
//            setContent("<br><br><br><hr>Message sent on "
//                    + getMessageDate()
//                    + "<br><hr>"
//                    + message.getContent());
        } catch (Exception ex) {
            userSessionManagerBean.setStatus(ex.toString());
        }

        return null;
    }

    /**
     * @param loadMessagePage the loadMessagePage to set
     */
    public void setLoadMessagePage(String loadMessagePage) {
        this.loadMessagePage = loadMessagePage;
    }

    /**
     * @return the userId
     */
    public String getUserId() {
        return userId;
    }

    /**
     * @param userId the userId to set
     */
    public void setUserId(String userId) {
        this.userId = userId;
    }

    /**
     * @return the loginManagerBean
     */
    public LoginManagerBean getLoginManagerBean() {
        return loginManagerBean;
    }

    /**
     * @param loginManagerBean the loginManagerBean to set
     */
    public void setLoginManagerBean(LoginManagerBean loginManagerBean) {
        this.loginManagerBean = loginManagerBean;
    }

    public void loadMessages() {
        if (userSessionManagerBean.getMessageType() != null) {
            if (userSessionManagerBean.getMessageType().equals("Inbox")) { //get inbox messages
                setMessages(messageSessionBeanLocal.getMessages(userSessionManagerBean.getUserId(), "inbox"));

                this.setCount(messages.size());

                if (messages.size() > 0) { //enable delete button
                    deleteButtonStatus = false;
                } else { //disable delete button
                    deleteButtonStatus = true;
                }
            } else { //get sent messages
                setMessages(messageSessionBeanLocal.getMessages(userSessionManagerBean.getUserId(), "sent"));

                this.setCount(messages.size());
                
                if (messages.size() > 0) { //enable delete button
                    deleteButtonStatus = false;
                } else { //disable delete button
                    deleteButtonStatus = true;
                }
            }
        }
    }

    public void redirect(ActionEvent event) { //to redirect somwhere
        String id = event.getComponent().getId();

        if (id.equals("sendMessage")) {
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/contactList.xhtml"); //redirect to contactList.xhtml
            } catch (Exception ex) {
                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
            }
        }
    }

    public void sendMessage(ActionEvent event) { //to send a message
        try {
            String msg = "";
            String[] temp;
            temp = userSessionManagerBean.getReceivers().split(","); //split users selected from contactList.xhtml into array

            if (temp.length > 0 && !subject.trim().equals("") && !content.replace("<br>", "").trim().equals("")) {
                for (int i = 0; i < temp.length; i++) { //loop through array to send message to each receipient
                    temp[i] = temp[i].trim();
                    if (!temp[i].equals("")) {
                        Employee owner = employeeSessionBeanLocal.getEmployee(temp[i]);

                        if (owner != null) { //if receipient exists
                            messageSessionBeanLocal.addMessage(userSessionManagerBean.getUserId(), temp[i], subject, content, owner);

                            owner = employeeSessionBeanLocal.getEmployee(userSessionManagerBean.getUserId());
                            messageSessionBeanLocal.addMessage(userSessionManagerBean.getUserId(), temp[i], subject, content, owner);
                        }
                    }
                }

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/messages.xhtml"); //redirect to messages.xhtml after sending message
            } else {
                msg += "<span><b>";

                if (temp.length == 0) {
                    msg += "Receipient cannot be empty.<br>";
                }

                if (subject.trim().equals("")) {
                    msg += "Subject cannot be empty.<br>";
                }

                if (content.replace("<br>", "").trim().equals("")) {
                    msg += "Content cannot be empty.<br>";
                }

                msg += "</b></span>";

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, ""));
            }
        } catch (Exception ex) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, ex.toString(), ""));
        }
    }

    public void replyMessage(ActionEvent event) {
        try {
            if (!content.replace("<br>", "").trim().equals("")) {
                Employee owner = employeeSessionBeanLocal.getEmployee(senderId);

                if (owner != null) {
                    messageSessionBeanLocal.addMessage(userSessionManagerBean.getUserId(), senderId, subject, content, owner);

                    owner = employeeSessionBeanLocal.getEmployee(userSessionManagerBean.getUserId());
                    messageSessionBeanLocal.addMessage(userSessionManagerBean.getUserId(), senderId, subject, content, owner);
                }

                FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                        + userSessionManagerBean.getServerName() + ":"
                        + userSessionManagerBean.getServerPort()
                        + "/MerlionERP-war/messages.xhtml"); //redirect to messages.xhtml after replying message
            } else {
                String msg = "<span><b>Content cannot be empty.</b></span>";

                FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, ""));
            }
        } catch (Exception ex) {
            userSessionManagerBean.setStatus(ex.toString());
        }
    }

    public void onRowSelect(SelectEvent event) { //to view and reply message selected
        try {
            userSessionManagerBean.setSelectedMessage(selectedMessage);

            if (selectedMessage.getMessageStatus() == false //if message is of unread status
                    && userSessionManagerBean.getMessageType().equals("Inbox") //if user is currently viewing inbox
                    && userSessionManagerBean.getUserId().equals(selectedMessage.getReceiverId())) {  //if the message's receiver is the user
                messageSessionBeanLocal.updateStatus(selectedMessage.getMessageId());
            }

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/replyMessage.xhtml"); //redirect to replyMessage.xhtml on message select
        } catch (Exception ex) {
            userSessionManagerBean.setStatus(ex.toString());
        }
    }

    public void deleteMessage(ActionEvent event) { //to delete selected messages
        try {
            for (Message m : messages) {
                if (selectedIds.get(m.getMessageId()).booleanValue()) {
                    messageSessionBeanLocal.deleteMessage(m.getMessageId());
                }
            }

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/messages.xhtml"); //redirect to messages.xhtml after deleting message
        } catch (Exception ex) {
            userSessionManagerBean.setStatus(ex.toString());
        }
    }

    /**
     * @return the receivers
     */
    public List<Employee> getReceivers() {
        return receivers;
    }

    /**
     * @param receivers the receivers to set
     */
    public void setReceivers(List<Employee> receivers) {
        this.receivers = receivers;
    }

    /**
     * @return the previousMessage
     */
    public String getPreviousMessage() {
        return previousMessage;
    }

    /**
     * @param previousMessage the previousMessage to set
     */
    public void setPreviousMessage(String previousMessage) {
        this.previousMessage = previousMessage;
    }

    /**
     * @return the selectedMessage
     */
    public Message getSelectedMessage() {
        return selectedMessage;
    }

    /**
     * @param selectedMessage the selectedMessage to set
     */
    public void setSelectedMessage(Message selectedMessage) {
        this.selectedMessage = selectedMessage;
    }

    public void loadChange() {
        try {
            userSessionManagerBean.setMessageType(type);

            FacesContext.getCurrentInstance().getExternalContext().redirect("http://"
                    + userSessionManagerBean.getServerName() + ":"
                    + userSessionManagerBean.getServerPort()
                    + "/MerlionERP-war/messages.xhtml"); //reload messages.xhtml on message select
        } catch (Exception ex) {
        }
    }

    /**
     * @return the selectedIds
     */
    public Map<Long, Boolean> getSelectedIds() {
        return selectedIds;
    }

    /**
     * @param selectedIds the selectedIds to set
     */
    public void setSelectedIds(Map<Long, Boolean> selectedIds) {
        this.selectedIds = selectedIds;
    }

    /**
     * @return the userSessionManagerBean
     */
    public UserSessionManagerBean getUserSessionManagerBean() {
        return userSessionManagerBean;
    }

    /**
     * @param userSessionManagerBean the userSessionManagerBean to set
     */
    public void setUserSessionManagerBean(UserSessionManagerBean userSessionManagerBean) {
        this.userSessionManagerBean = userSessionManagerBean;
    }

    /**
     * @return the selectedMessages
     */
    public List<Message> getSelectedMessages() {
        return selectedMessages;
    }

    /**
     * @param selectedMessages the selectedMessages to set
     */
    public void setSelectedMessages(List<Message> selectedMessages) {
        this.selectedMessages = selectedMessages;
    }

    /**
     * @return the isReceiver
     */
    public Boolean getIsInbox() {
        if (userSessionManagerBean.getMessageType().equals("Inbox")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * @param isInbox the isInbox to set
     */
    public void setIsInbox(Boolean isInbox) {
        this.isInbox = isInbox;
    }

    /**
     * @return the deleteButtonStatus
     */
    public Boolean getDeleteButtonStatus() {
        return deleteButtonStatus;
    }

    /**
     * @param deleteButtonStatus the deleteButtonStatus to set
     */
    public void setDeleteButtonStatus(Boolean deleteButtonStatus) {
        this.deleteButtonStatus = deleteButtonStatus;
    }
}
